//
//  AXNetworkTools.m
//  网络访问框架(AFN)封装-OC
//
//  Created by Alex on 16/11/13.
//  Copyright © 2016年 Alex. All rights reserved.
//

#import "AXNetworkTools.h"

//声明协议
@protocol HTTPProxy <NSObject>
//欺骗编译 在编译时期不报错,并且给一个只能提示
@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end

//遵守协议
@interface AXNetworkTools ()<HTTPProxy>

@end

@implementation AXNetworkTools

+(instancetype)shared {
    static AXNetworkTools *tools;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        tools = [[self alloc]init];
        
        //可能需要设置响应的序列化器和请求的序列化器
        tools.responseSerializer.acceptableContentTypes = [tools.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
        
    });
    return tools;
}

-(void)requestWithHTTPMethod:(HTTPMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(void (^)(id, NSError *))finished
{
    //成功block
    void(^successCallback)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功的回调
        finished(responseObject,nil);
    };
    
    //失败block
    void(^failureCallBack)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil,error);
        //错误的统一输出
        NSLog(@"-----------------------发生错误-----------------------");
        NSLog(@"%@",error);
    };
    
    //获取访问方式的String
    NSString *methodString = (method == GET ? @"GET" : @"POST");
    
    //OC有消息机制 (此为私有方法,上面定义协议便可访问)
    [[self dataTaskWithHTTPMethod:methodString URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:successCallback failure:failureCallBack] resume];
    

}
@end
